package com.gitee.yusugar.core.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.yusugar.common.YuToolServiceException;
import com.gitee.yusugar.core.task.enums.TaskType;
import com.gitee.yusugar.core.task.pojo.TimerInfo;

import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * 定时任务生成工具类
 *
 * @author Y.sugar
 * @since 2023/7/25 15:02
 */
public class TaskUtil {

    public static final ScheduledExecutorService TASK = new ScheduledThreadPoolExecutor( 10 );

    public static void create(Runnable runnable, TimerInfo timerInfo) throws ExecutionException, InterruptedException {
        DateTime startTime = DateUtil.parseDateTime(TimerGenerator.create(timerInfo, DateUtil.now()));
        while (true){
            ScheduledFuture<?> schedule = TASK.schedule(runnable, DateUtil.date().between(startTime, DateUnit.SECOND), TimeUnit.SECONDS);
            startTime = DateUtil.parseDateTime(TimerGenerator.create(timerInfo, startTime.offset(DateField.SECOND, 1).toString()));
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //System.out.println(TimerGenerator.createFillZero("* * * 10-12 20-55 10,20,30,50 1-3"));
        //System.out.println(TimerGenerator.createFillZero("2023 1,5,9,10 12-15 8 13,30,40 25,30", "2023-09-13 08:13:26"));
        create(() -> {
            System.out.println(DateUtil.now() + " 任务");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, TimerGenerator.convert("* * * * * 0,5,10,15,20,25,30,35,40,45,50,55 1-3"));
        System.out.println("完毕");
    }
}
